<template>
  <el-card class="box-card">
    <!-- 卡片顶部添加按钮 -->
    <el-button
      @click="addTrademark"
      type="primary"
      size="default"
      icon="Plus"
      v-has="'btn.Trademark.add'"
    >
      添加品牌
    </el-button>
    <!-- 表格组件 -->
    <el-table :data="trademarkArr" style="margin: 10px 0px" border>
      <!-- 展示数据默认用的div，不想用可以使用插槽 -->
      <el-table-column
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTrademark(row)"
          ></el-button>

          <el-popconfirm
            :title="`确定删除${row.tmName}？`"
            width="250px"
            icon="Delete"
            @confirm="removeTradeMark(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @current-change="changePageNo"
      @size-change="sizeChange"
      v-model:current-page="pageNo"
      :page-sizes="[3, 5, 7, 9]"
      v-model:page-size="limit"
      layout="prev, pager, next, jumper, ->, total, sizes"
      :pager-count="9"
      background
      :total="total"
    ></el-pagination>
  </el-card>

  <!-- 对话框组件 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
  >
    <el-form
      ref="formRef"
      :model="trademarkParams"
      :rules="rules"
      label-width="80px"
      style="width: 80%"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input
          placeholder="请输入品牌名称"
          v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <!-- 请求路径必须带api，不然代理服务器不认 -->
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <!-- 具名插槽：底部按钮区 -->
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, UploadProps } from 'element-plus';
import { ref, reactive, onMounted, nextTick } from 'vue';
//导入接口
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark';
//导入类型
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type';

//按钮权限实现
// import useUserStore from '@/store/modules/user';
// let userStore = useUserStore()

let pageNo = ref<number>(1); //当前页码
let limit = ref<number>(3); //每页展示多少条
let total = ref<number>(0); //品牌总数

let dialogFormVisible = ref<boolean>(false); //对话框显示隐藏

let trademarkArr = ref<Records>([]); //已有品牌数据

//收集新增品牌的数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
});

//获取el-form组件实例
let formRef = ref();
//自定义校验规则
const validatorTmName = (_rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack();
  } else {
    callBack(new Error('品牌名称字数不能小于2'));
  }
};
const validatorLogoUrl = (_rule: any, value: any, callBack: any) => {
  if (value) {
    callBack();
  } else {
    callBack(new Error('必须传入图片'));
  }
};

//表单校验规则对象
const rules = {
  tmName: [{ required: true, trigger: blur, validator: validatorTmName }],
  logoUrl: [
    {
      required: true,
      validator: validatorLogoUrl,
    },
  ],
};

//获取已有品牌
const getHasTrademark = async (pager = 1) => {
  //当前页码
  pageNo.value = pager;
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  );
  if (result.code == 200) {
    total.value = result.data.total;
    trademarkArr.value = result.data.records;
  }
};

//组件挂载完毕
onMounted(() => {
  getHasTrademark();
});

//上传图片之前钩子，限定一下文件类型和大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //要求png、jpeg、gif 4M
  if (
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/jpeg' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 10124 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小要小于4M',
      });
      return false;
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式必须为png、jpeg、gif',
    });
    return false;
  }
};
//图片上传完成后触发
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  _uploadFile,
) => {
  //收集url，点击添加时带给服务器
  trademarkParams.logoUrl = response.data;
  //清除校验结果
  formRef.value.clearValidate('logoUrl');
};

//页码改变触发 自动注入当前页码
const changePageNo = (page: number) => {
  getHasTrademark(page);
};
//页码展示数量的下拉菜单改变时触发
const sizeChange = () => {
  getHasTrademark();
};

//添加按钮
const addTrademark = () => {
  dialogFormVisible.value = true;
  //清空数据，在取消和确定按钮就不用写了
  trademarkParams.id = 0;
  trademarkParams.tmName = '';
  trademarkParams.logoUrl = '';
  //清理校验规则
  nextTick(() => {
    formRef.value.clearValidate('tmName');
    formRef.value.clearValidate('logoUrl');
  });
};
//修改按钮
const updateTrademark = (row: any) => {
  //清空校验规则错误提示信息
  nextTick(() => {
    formRef.value.clearValidate('tmName');
    formRef.value.clearValidate('logoUrl');
  });
  //对话框显示
  dialogFormVisible.value = true;
  //ES6语法合并对象
  Object.assign(trademarkParams, row);
};

//对话框按钮
const cancel = () => {
  dialogFormVisible.value = false;
};
//添加品牌
const confirm = async () => {
  //发请求之前表单校验
  await formRef.value.validate();

  let res = await reqAddOrUpdateTrademark(trademarkParams);
  if (res.code == 200) {
    dialogFormVisible.value = false;
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    });
    //编辑的话在当前页刷新
    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
    //清空数据
    trademarkParams.tmName = '';
    trademarkParams.logoUrl = '';
  } else {
    dialogFormVisible.value = false;
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    });
  }
};

//删除的气泡确认框 回调
const removeTradeMark = async (id: number) => {
  let res = await reqDeleteTrademark(id);
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    });
    //当前页不足一条就去前一页
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    );
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    });
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
